import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @version 1.0
 * @autho 3505
 * @date 2018/5/22
 */
public class ServeMachine {
    static String str2;
    public static void send(String IP,String speak){
        DatagramPacket datagramPacket=null;
        DatagramSocket datagramSocket=null;
        try {
            datagramSocket=new DatagramSocket(9090);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        Scanner scanner=new Scanner(System.in);
            String str=speak+str2;
            byte[] by = str.getBytes();
            try {

                datagramPacket = new DatagramPacket(by, 0, by.length, InetAddress.getByName(IP), 9000);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
//            System.out.println("正在发送数据");
            try {
                datagramSocket.send(datagramPacket);
                datagramSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

    }
    public static void sendMany(String str1[]){
        for (int a=0;a<str1.length-1;a++){
            send(str1[a],str1[str1.length-1]);
        }
    }
    public static void main(String[] args) {
        DatagramSocket datagramSocket=null;
        try {
            datagramSocket=new DatagramSocket(9000);
        }catch (Exception E){
            E.printStackTrace();
        }
        byte[] by=new byte[1024];
        DatagramPacket datagramPacket=new DatagramPacket(by,by.length);
        System.out.println("等待接收数据...");
        while (true) {
            try {
                datagramSocket.receive(datagramPacket);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //接收信息
            String str = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
            //解析信息
             str2="-->发送主机地址" +datagramPacket.getAddress().getHostAddress();
            String str1[]=str.split(",");
            //分别发送信息
            if (str1.length>=3){
                sendMany(str1);
            }
            else if (str1.length==2){
                send(str1[0],str1[1]);
            }

            System.out.println(str + "-->发送主机地址" + datagramPacket.getAddress().getHostAddress() );
//            System.out.println(str + "-->发送主机地址" + datagramPacket.getAddress().getHostAddress() + " : 端口号" + datagramPacket.getPort());
        }

    }
}
